package src.com.zuiacsn;

import src.com.test.Student;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/*
* 获取类的成员变量
* */
public class Demo3 {
    public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<Student> studentClass = Student.class;
        // 获取类的全部成员变量(只能获取public修饰)
        Field[] fields = studentClass.getFields();
        for (Field field : fields) {
            System.out.println(field.getName()+" "+field.getType());
        }
        System.out.println("--------------------------");

        // 获取类的全部成员变量(只要存在就能获取)
        Field[] declaredFields = studentClass.getDeclaredFields();
        System.out.println("--------------------------");


        // 获取单个成员变量(只能获取public修饰)
        Field field = studentClass.getField("age");
        System.out.println(field);
        System.out.println("--------------------------");

        // 获取单个成员变量(只要存在就能获取)
        Field name = studentClass.getDeclaredField("name");
        System.out.println(name);
        System.out.println("--------------------------");

        /*
        * 获取成员变量的作用依然是赋值,取值
        * void set(Object obj,Object value) 为obj对象里的成员变量赋值为value
        * Object get(Object obj) 取出obj对象中的值
        * public void setAccessible(Boolean flag) 设置为true,表示禁止检查访问控制(暴力反射)
        * */

        Constructor<Student> declaredConstructor = studentClass.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        Student student = declaredConstructor.newInstance();
        name.set(student,"张三");
        Object o = name.get(student);
        System.out.println(o);
    }
}
